<script setup lang="tsx">
import { Popconfirm, Tag } from 'ant-design-vue';
import { ref } from 'vue';
import { fetchBatchDeleteUsers, fetchDeleteUser, fetchGetUserList } from '@/service/api';
import { useTable, useTableOperate, useTableScroll } from '@/hooks/common/table';
import { $t } from '@/locales';
import { enableStatusRecord, userGenderRecord } from '@/constants/business';
import TableHeaderOperation from '@/components/advanced/table-header-operation.vue';
import AuthButton from '@/components/common/auth-button.vue';
import ViewDrawer from '@/components/common/view-drawer.vue';
import BusinessCard from '@/components/common/business-card.vue';
import UserOperateDrawer from './modules/user-operate-drawer.vue';
import UserSearch from './modules/user-search.vue';

const { tableWrapperRef, scrollConfig } = useTableScroll();

const {
  columns,
  columnChecks,
  data,
  getData,
  getDataByPage,
  loading,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: fetchGetUserList,
  apiParams: {
    current: 1,
    size: 10,
    // if you want to use the searchParams in Form, you need to define the following properties, and the value is null
    // the value can not be undefined, otherwise the property in Form will not be reactive
    status: undefined,
    userName: undefined,
    userGender: undefined,
    nickName: undefined,
    userPhone: undefined,
    userEmail: undefined
  },
  columns: () => [
    {
      key: 'index',
      title: $t('common.index'),
      dataIndex: 'index',
      align: 'center' as const,
      width: 64
    },
    {
      key: 'userName',
      dataIndex: 'userName',
      title: $t('page.manage.user.userName'),
      align: 'center' as const,
      minWidth: 100
    },
    {
      key: 'userGender',
      title: $t('page.manage.user.userGender'),
      align: 'center' as const,
      dataIndex: 'userGender',
      width: 100,
      customRender: ({ record }: { record: any }) => {
        if (record.userGender === null) {
          return null;
        }

        const tagMap: Record<Api.SystemManage.UserGender, string> = {
          1: 'processing',
          2: 'error'
        };

        const label = $t(userGenderRecord[record.userGender as Api.SystemManage.UserGender]);

        return <Tag color={tagMap[record.userGender as Api.SystemManage.UserGender]}>{label}</Tag>;
      }
    },
    {
      key: 'nickName',
      dataIndex: 'nickName',
      title: $t('page.manage.user.nickName'),
      align: 'center' as const,
      minWidth: 100
    },
    {
      key: 'userPhone',
      dataIndex: 'userPhone',
      title: $t('page.manage.user.userPhone'),
      align: 'center' as const,
      width: 120
    },
    {
      key: 'userEmail',
      dataIndex: 'userEmail',
      title: $t('page.manage.user.userEmail'),
      align: 'center' as const,
      minWidth: 200
    },
    {
      key: 'userRoles',
      dataIndex: 'userRoles',
      title: $t('page.manage.user.userRole'),
      align: 'center' as const,
      minWidth: 150,
      customRender: ({ record }: { record: any }) => {
        // 处理角色显示，支持多种格式
        let roles: string[] = [];
        const userRecord = record as any;

        if (userRecord.roles && typeof userRecord.roles === 'string') {
          // 如果是JSON格式，尝试解析
          if (userRecord.roles.startsWith('[') && userRecord.roles.endsWith(']')) {
            try {
              const rolesStr = userRecord.roles.substring(1, userRecord.roles.length - 1);
              if (rolesStr.trim()) {
                roles = rolesStr.split(',').map((role: string) => role.trim().replace(/"/g, ''));
              }
            } catch {
              roles = [];
            }
          } else {
            // 逗号分隔的字符串
            roles = userRecord.roles.split(',').filter((role: string) => role.trim() !== '');
          }
        } else if (userRecord.userRoles && typeof userRecord.userRoles === 'string') {
          // 兼容旧的userRoles字符串格式
          roles = userRecord.userRoles.split(',').filter((role: string) => role.trim() !== '');
        } else if (Array.isArray(userRecord.userRoles)) {
          roles = userRecord.userRoles;
        }

        if (roles.length === 0) {
          return <span class="text-gray-400">-</span>;
        }

        return (
          <div class="flex flex-wrap justify-center gap-4px">
            {roles.map((role: string) => (
              <Tag key={role} color="blue">
                {role}
              </Tag>
            ))}
          </div>
        );
      }
    },
    {
      key: 'status',
      dataIndex: 'status',
      title: $t('page.manage.user.userStatus'),
      align: 'center' as const,
      width: 100,
      customRender: ({ record }: { record: any }) => {
        if (record.status === null) {
          return null;
        }

        const tagMap: Record<Api.Common.EnableStatus, string> = {
          1: 'success',
          2: 'warning'
        };

        const label = $t(enableStatusRecord[record.status as Api.Common.EnableStatus]);

        return <Tag color={tagMap[record.status as Api.Common.EnableStatus]}>{label}</Tag>;
      }
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center' as const,
      width: 180,
      customRender: ({ record }: { record: any }) => (
        <div class="flex-center gap-8px">
          <AuthButton permission="USER_VIEW" onClick={() => handleView(record)} type="primary" ghost size="small">
            {$t('common.view')}
          </AuthButton>
          <AuthButton permission="USER_EDIT" onClick={() => edit(record.id)} type="primary" ghost size="small">
            {$t('common.edit')}
          </AuthButton>
          <Popconfirm title={$t('common.confirmDelete')} onConfirm={() => handleDelete(record.id)}>
            <AuthButton permission="USER_DELETE" danger size="small">
              {$t('common.delete')}
            </AuthButton>
          </Popconfirm>
        </div>
      )
    }
  ]
});

const {
  drawerVisible,
  operateType,
  editingData,
  handleAdd,
  handleEdit,
  checkedRowKeys,
  rowSelection,
  onBatchDeleted,
  onDeleted
  // closeDrawer
} = useTableOperate(data, getData);

// 查看功能状态
const viewDrawerVisible = ref(false);
const viewingData = ref<Api.SystemManage.User | null>(null);

async function handleBatchDelete() {
  try {
    const { error: err } = await fetchBatchDeleteUsers(checkedRowKeys.value.map(id => Number(id)));
    if (!err) {
      onBatchDeleted();
    }
  } catch {
    window.$message?.error('操作失败');
  }
}

async function handleDelete(id: number) {
  try {
    const { error: err } = await fetchDeleteUser(id);
    if (!err) {
      onDeleted();
    }
  } catch {
    window.$message?.error('操作失败');
  }
}

function edit(id: number) {
  handleEdit(id);
}

// 查看用户详情
function handleView(record: Api.SystemManage.User) {
  viewingData.value = record;
  viewDrawerVisible.value = true;
}
</script>

<template>
  <div class="business-style min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <UserSearch
      v-model:model="searchParams"
      @reset="
        () => {
          resetSearchParams();
          getDataByPage();
        }
      "
      @search="getDataByPage"
    />

    <BusinessCard
      :title="$t('page.manage.user.title')"
      :body-style="{ flex: 1, overflow: 'hidden' }"
      class="flex-col-stretch sm:flex-1-hidden"
    >
      <template #extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          add-permission="USER_ADD"
          delete-permission="USER_DELETE"
          @add="handleAdd"
          @delete="handleBatchDelete"
          @refresh="getData"
        />
      </template>

      <ATable
        ref="tableWrapperRef"
        :columns="columns"
        :data-source="data"
        size="small"
        :row-selection="rowSelection"
        :scroll="scrollConfig"
        :loading="loading"
        row-key="id"
        :pagination="mobilePagination"
        class="h-full"
      />

      <UserOperateDrawer
        v-model:open="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData || undefined"
        @submitted="getDataByPage"
      />

      <!-- 查看用户详情抽屉 -->
      <ViewDrawer v-model:model-value="viewDrawerVisible" title="查看用户详情" :width="600">
        <div v-if="viewingData" class="user-view-content">
          <ARow :gutter="16">
            <ACol :span="12">
              <div class="info-item">
                <label class="info-label">用户名：</label>
                <span class="info-value">{{ viewingData.userName }}</span>
              </div>
            </ACol>
            <ACol :span="12">
              <div class="info-item">
                <label class="info-label">昵称：</label>
                <span class="info-value">{{ viewingData.nickName || '-' }}</span>
              </div>
            </ACol>
            <ACol :span="12">
              <div class="info-item">
                <label class="info-label">手机号：</label>
                <span class="info-value">{{ viewingData.userPhone || '-' }}</span>
              </div>
            </ACol>
            <ACol :span="12">
              <div class="info-item">
                <label class="info-label">邮箱：</label>
                <span class="info-value">{{ viewingData.userEmail || '-' }}</span>
              </div>
            </ACol>
            <ACol :span="12">
              <div class="info-item">
                <label class="info-label">性别：</label>
                <span class="info-value">
                  <ATag v-if="viewingData.userGender" :color="Number(viewingData.userGender) === 1 ? 'blue' : 'pink'">
                    {{ Number(viewingData.userGender) === 1 ? '男' : '女' }}
                  </ATag>
                  <span v-else>-</span>
                </span>
              </div>
            </ACol>
            <ACol :span="12">
              <div class="info-item">
                <label class="info-label">状态：</label>
                <span class="info-value">
                  <ATag v-if="viewingData.status" :color="Number(viewingData.status) === 1 ? 'success' : 'warning'">
                    {{ Number(viewingData.status) === 1 ? '启用' : '禁用' }}
                  </ATag>
                  <span v-else>-</span>
                </span>
              </div>
            </ACol>
            <ACol :span="24">
              <div class="info-item">
                <label class="info-label">角色：</label>
                <span class="info-value">
                  <div v-if="viewingData.userRoles" class="flex flex-wrap gap-2">
                    <ATag v-for="role in viewingData.userRoles" :key="role" color="blue">
                      {{ role }}
                    </ATag>
                  </div>
                  <span v-else>-</span>
                </span>
              </div>
            </ACol>
          </ARow>
        </div>
      </ViewDrawer>
    </BusinessCard>
  </div>
</template>

<style scoped>
.user-view-content {
  padding: 16px 0;
}

.info-item {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}

.info-label {
  font-weight: 500;
  color: #666;
  min-width: 80px;
  margin-right: 8px;
}

.info-value {
  color: #333;
  flex: 1;
}

/* 暗色主题适配 */
.dark .info-label {
  color: #999;
}

.dark .info-value {
  color: #ccc;
}
</style>
